<?php

namespace app\admin\service;

use app\model\ResponsibilityPerson;
use app\model\Company;
use app\common\Error;
use app\common\Common;
use think\facade\Db;

class ResponsibilityPersonService
{
    private $model;
    private $companyModel;

    public function __construct(ResponsibilityPerson $model, Company $companyModel)
    {
        $this->model = $model;
        $this->companyModel = $companyModel;
    }

    // 添加/编辑负责人
    public function editResponsibilityPerson(array $params)
    {
        if (empty($params['id'])) {
            $data = $this->model->getInfoByWhere(['name' => $params['name']]);

            if ($data) {
                return ['message' => Error::NAME_OF_THE_RESPONSIBLE_PERSON_ALREADY_EXISTS];
            }

            $params['created_at'] = time();
            $params['password'] = password_hash($params['password'], PASSWORD_DEFAULT);

            if (!empty($params['is_distributor'])) {
                $params['token'] = Common::createToken(date('His'));
            }

        } else {
            $params['updated_at'] = time();

            $data = $this->model->getInfoById($params['id'], 'password, token');

            if ($data['password'] != $params['password']) { // 修改过
                $params['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
            }

            if (empty($data['token']) && !empty($params['is_distributor'])) {
                $params['token'] = Common::createToken(date('His'));
            }
        }

        $id = $this->model->edit($params);

        if (!$id) {
            return false;
        }

        return true;
    }

    // 获取负责人列表
    public function getResponsibilityPersonList(array $params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];
        // 公司名称搜索
        if (!empty($params['company_name'])) {
            $where[] = ['c.name', 'like', '%' . $params['company_name'] . '%'];
        }
        // 名称搜索
        if (!empty($params['name'])) {
            $where[] = ['r.name', 'like', '%' . $params['name'] . '%'];
        }
        // 分销商管理搜索
        if (isset($params['is_distributor']) && is_numeric($params['is_distributor'])) {
            $where[] = ['r.is_distributor', '=', $params['is_distributor']];
        }
        // 分公司管理搜索
        if (isset($params['is_branch_office_manage']) && is_numeric($params['is_branch_office_manage'])) {
            $where[] = ['r.is_branch_office_manage', '=', $params['is_branch_office_manage']];
        }

        $data = $this->model->getPagingDataByWhere($where, $page, $limit, 'r.id, r.name, c.name as company_name, r.official_account_id, r.is_distributor, r.scale, r.pid, r.commission_scale, r.video_ids, r.pid, r.token, r.wechat_applet_commission_scale, r.is_branch_office_manage,is_depart');

        if ($data['data']) {

            $pids = array_column($data['data'], 'pid');

            $pidData = $this->model->getDataByWhere(['id' => $pids], 'id, name');
            $pNames = array_column($pidData, 'name', 'id');

            foreach ($data['data'] as $key => $item) {
                $data['data'][$key]['official_account_id'] = explode(',', $item['official_account_id']);
                $data['data'][$key]['video_ids'] = empty($item['video_ids']) ? [] : explode(',', $item['video_ids']);

                $data['data'][$key]['p_name'] = empty($pNames[$item['pid']]) ? '' : $pNames[$item['pid']];
            }
        }

        return $data;
    }

    // 获取负责人详情
    public function getResponsibilityPersonDetail($id)
    {
        $data =  $this->model->getInfoById($id, 'id, name, company_id, official_account_id, password, is_distributor, scale, commission_scale, video_ids, token, wechat_applet_commission_scale, is_branch_office_manage, is_depart');

        $data['official_account_id'] = explode(',', $data['official_account_id']);

        return $data;
    }

    // 删除负责人
    public function deleteResponsibilityPerson($id)
    {
        $bool = $this->model->destroy($id);

        if (!$bool) {
            return false;
        }

        return true;
    }

    // 负责人下拉列表
    public function getSelectList($params)
    {
        $where = [];
        if (!empty($params['type'])) {
            if($params['type']==2){
                $where = [
                    ['company_id', '=', $params['company_id']],
                ];
                $data = $this->model->getDataByWhere($where, 'id as responsibility_person_id, name as responsibility_person_name');
    
                return $data;
            }else{
                $where = [
                    ['is_distributor', '=', 0],
                    ['is_branch_office_manage', '=', 0],
                    ['pid', 'EXP', Db::raw('IS NULL')]
                ];
    
                $branchOfficeManage = $this->model->getDataByWhere(['is_branch_office_manage' => 1], 'id');
                $manageIds = array_column($branchOfficeManage, 'id');
    
                $branchOfficeLaunch = $this->model->getDataByWhere(['pid' => $manageIds], 'id as responsibility_person_id, name as responsibility_person_name');
    
                $data = $this->model->getDataByWhere($where, 'id as responsibility_person_id, name as responsibility_person_name');
    
                return array_merge($branchOfficeLaunch, $data);
            }
           
        }
        $data = $this->model->getDataByWhere($where, 'id as responsibility_person_id, name as responsibility_person_name');
        return $data;
    }

    // 负责人下拉列表
    public function getDistributorSelect($params)
    {
        $data = $this->model->getDataByWhere(['is_distributor' => 1], 'id as responsibility_person_id, name as responsibility_person_name');
        return $data;
    }
}